package com.tuling.stu.common;

import java.lang.reflect.Field;

/**
 * 一道面试题引发的无限思考
 * 主方法定义两个Integer变量，并赋值
 * 然后通过一个swap()方法
 * 
 * @author chenhs
 * Created on 2017年12月13日 上午10:42:04
 */
public class Test {

	public static void main(String[] args) {
		/*
		Integer a = 127;
		Integer b = 127;
		System.out.println(a == b);	//true or false?
		*/
		
		
		Integer a = 1;	//装箱 Integer a = Integer.valueOf(1);
		Integer b = 2;	
		
		System.out.println("before swap : a = "+ a +", b = " + b);
		swap(a, b);
		System.out.println("after swap : a = "+ a +", b = " + b);
		
	}
	
	private static void swap(Integer num1, Integer num2) {
	/*	Integer tmp = num1;
		num1 = num2;
		num2 = tmp;*/
		
		try {
			Field field = Integer.class.getDeclaredField("value");
			field.setAccessible(true);
			int tmp = num1.intValue();	//1
			field.set(num1, num2);		// IntegerCache的值下标为129 赋值为2
			field.set(num2, new Integer(tmp));		// tmp所在IntegerCache的值为下标129的值: 2
		}  catch (Exception e) {
			e.printStackTrace();
		}
		/*
		try {
			Field field = Integer.class.getDeclaredField("value");
			field.setAccessible(true);
			int tmp = num1.intValue();	//1
			field.setInt(num1, num2);		// IntegerCache的值下标为129 赋值为2
			field.setInt(num2, tmp);		// tmp所在IntegerCache的值为下标129的值: 2
		}  catch (Exception e) {
			e.printStackTrace();
		}
		*/
	}

}
